#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "protocol.h"


int get_dev_ip(char *dev_name, ip_t *p_ip)
{
	int inet_sock;
	struct ifreq ifr;

	inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
	strcpy(ifr.ifr_name, dev_name);
	if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
	{
		perror("ioctl");
		return 1;
	}
	close(inet_sock);
	memcpy(p_ip,&(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr), sizeof(ip_t));

	return 0;
}

int get_dev_mac(char *dev_name, mac_t *p_mac)
{
	int inet_sock;
	struct ifreq ifr;

	inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
	strcpy(ifr.ifr_name, dev_name);
	if (ioctl(inet_sock, SIOCGIFHWADDR, &ifr) < 0)
	{
		perror("ioctl");
		return 1;
	}
	close(inet_sock);
	memcpy(p_mac,ifr.ifr_hwaddr.sa_data, sizeof(mac_t));

	return 0;
}

int get_gateway_ip(ip_t *p_ip)
{
	int ret;
	FILE *fp;
	char buf[16];
	char *script = "route -n | awk '$1~/0.0.0.0/{printf(\"%s\",$2);}';";	

	fp = popen(script, "r");
	if(fp == NULL)
	{
		fprintf(stderr,"excute script failed\n");
		return 1;
	}

	ret = fread(buf, 1, sizeof(buf), fp);
	if(ret < 7 || ret > 15)
	{
		fprintf(stderr,"read result failed: ret = %d\n", ret);
		pclose(fp);
		return 1;
	}
	pclose(fp);

	buf[ret] = '\0';
	return !inet_aton(buf, (struct in_addr *)p_ip);
}


